#include "FileDialog.hpp"

FileDialog::FileDialog(int x, int y):Window(){
    drawList = new ScrollPanel(0, 0, rect.width - 5, rect.height - 15,
        Panel::HorizontalStretch | Panel::VerticalStretch);
    add(drawList);
    setPosition(x, y);
    setSize(500, 300);
    setTitle("Open File");
    
    loadPath(fs::system_complete(fs::current_path()));
    
}

/**
* Tell FileDialog to open selected file. If the file
* is a folder then the new path is loaded.
* @param name Name of file to open.
* @return False if path has changed, True otherwise.
*/
bool FileDialog::selectedFile(std::string name){
    
	//Check for the special parent entry.
    if(name.compare("..") == 0){
        loadPath(currentPath.parent_path());
        return false;
    }
    
	//Loop all files in current path and find one selected.
	fs::directory_iterator end_itr;
    for(fs::directory_iterator itr(currentPath); itr != end_itr; ++itr ){
        if(name == itr->path().filename()){
			//If given file is a directory then change path, otherwise do
			//nothing and return false.
            if(is_directory(itr->path())){
                loadPath(itr->path());
                return false;
            }
            else
                return true;
        }
    }
}

/** 
* Open given filepath in FileDialog.
* @param filepath Path to open.
*/
void FileDialog::loadPath(fs::path filepath){
    for(int i = 0; i < drawList->elements.size(); i++){
        delete drawList->elements.at(i);
    }
    drawList->interfaceElements.clear();
    drawList->elements.clear();

    
    currentPath = filepath;
    fs::directory_iterator end_itr;
    int yPos = 0;
    
    if(currentPath.has_parent_path()){
        Label* prev = new Label(0, yPos, 12, sf::Color::White, "..");
        prev->rect.height = 13;
        prev->rect.width = 30;
        drawList->add(prev);
        yPos += prev->rect.height;
    }
    for(fs::directory_iterator itr(filepath); itr != end_itr; ++itr ){
		Label* file = new Label(0, yPos, 12, sf::Color::White, itr->path().filename().string());
        yPos += file->rect.height + 1;
        drawList->add(file);
    }
    drawList->updateScrollView();
}
